// 1. 搭建网站服务器，实现客户端与服务端的通信
// 2. 连接数据库，创建用户集合，向集合中插入文档
// 3. 当用户访问/list时，将所有用户信息查询出来
   //实现路由功能
   //呈现用户列表
   //从数据库查询数据并展示
// 4. 将用户信息和表格HTML进行拼接并将拼接结果响应回客户端
// 5. 当用户访问/add时，呈现表单页面，并实现添加用户信息功能
// 6. 当用户访问/modify时，呈现修改页面，并实现修改用户信息功能
// 7. 当用户访问/delete时，实现用户删除功能
const http = require('http');
const url = require('url');
const querystring = require('querystring');
require('./model/index');
const user = require('./model/user')
//创建服务器
const app = http.createServer();

//为服务器对象添加请求时间
app.on('request', async(req,res)=>{
  //请求方式
  const method = req.method;
  const {pathname,query} = url.parse(req.url,true);
  if(method == 'GET') {
    //呈现用户列表页面
    if(pathname == '/list') {
      let users = await user.find();
      let list = `
      <!DOCTYPE html>
      <html>
      <head>
        <meta charset="utf-8"> 
        <title>列表</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">  
      </head>
      <body>
        
      <div class="container">
        <a href="/add" type="button"  class="btn btn-primary">添加</a>     
        <table class="table">
          <thead>
            <tr>
              <th>用户名</th>
              <th>年龄</th>
              <th>邮箱</th>
              <th>爱好</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
      `;
      users.forEach((item,index)=>{
        list += `
        <tr>
        <td>${item.name}</td>
        <td>${item.age}</td>
        <td>${item.email}</td>
        <td>
        `
        item.hobbies.forEach(_item=>{
          list+=`
          <span>${_item}</span>
          `
        })
          
        list +=`</td>
        <td><a href="/remove?id=${item._id}" class="btn btn-primary btn-xs">删除</a>
        <a href="/modify?id=${item._id}" class="btn btn-default btn-xs">修改</a></td>
      </tr>
        `
      })
      list+=`
          </tbody>
        </table>
      </div>
      </body>
      </html>`;
      res.end(list);
    } else if(pathname == '/add') {
      let add =`
      <!DOCTYPE html>
      <html>
      <head>
        <meta charset="utf-8"> 
        <title>Bootstrap 实例 - 基本表单</title>
        <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">  
      </head>
      <body>
      <h2>添加用户</h2>
      <form method="post" action="/add">
        <div class="form-group">
          <label for="name">用户名</label>
          <input type="text" class="form-control" name="name" 
               placeholder="请输入用户名">
        </div>
        <div class="form-group">
          <label for="name">密码</label>
          <input type="password" class="form-control" name="password" 
               placeholder="请输入密码">
        </div>
        <div class="form-group">
          <label for="name">年龄</label>
          <input type="text" class="form-control" name="age" 
               placeholder="请输入年龄">
        </div>
        <div class="form-group">
          <label for="name">邮箱</label>
          <input type="text" class="form-control" name="email" 
               placeholder="请输入邮箱">
        </div>
        <div class="form-group">
          <label>请选择爱好</label>
          <div>
            <label class="checkbox-inline"><input type="checkbox" value="打游戏" name="hobbies"> 打游戏</label>
            <label class="checkbox-inline"><input type="checkbox" value="篮球" name="hobbies"> 篮球</label>
            <label class="checkbox-inline"><input type="checkbox" value="唱歌" name="hobbies"> 唱歌</label>
            <label class="checkbox-inline"><input type="checkbox" value="写字" name="hobbies"> 写字</label>
            <label class="checkbox-inline"><input type="checkbox" value="游泳" name="hobbies"> 游泳</label>
            <label class="checkbox-inline"><input type="checkbox" value="读书" name="hobbies"> 读书</label>
          </div>
        </div>
        <button type="submit" class="btn btn-default">添加用户</button>
      </form>
        
      </body>
      </html>
      `;
      res.end(add);
    } else if(pathname == '/modify') {
      let usedata = await user.findOne({_id:query.id});
      let hobbies = ['打游戏','读书','唱歌','写字','游泳']
      let modify = `
      <!DOCTYPE html>
      <html>
      <head>
        <meta charset="utf-8"> 
        <title>Bootstrap 实例 - 基本表单</title>
        <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">  
      </head>
      <body>
      <h2>修改用户</h2>
      <form method="post" action="/modify?id=${query.id}">
        <div class="form-group">
          <label for="name">用户名</label>
          <input type="text" class="form-control" name="name" value="${usedata.name}"
               placeholder="请输入用户名">
        </div>
        <div class="form-group">
          <label for="name">密码</label>
          <input type="password" class="form-control" name="password"  value="${usedata.password}"
               placeholder="请输入密码">
        </div>
        <div class="form-group">
          <label for="name">年龄</label>
          <input type="text" class="form-control" name="age"  value="${usedata.age}"
               placeholder="请输入年龄">
        </div>
        <div class="form-group">
          <label for="name">邮箱</label>
          <input type="text" class="form-control" name="email"  value="${usedata.email}"
               placeholder="请输入邮箱">
        </div>
        <div class="form-group">
          <label>请选择爱好</label>
          <div>
          `;
          hobbies.forEach(item=>{
            let isHobby = usedata.hobbies.includes(item);
            if(isHobby) {
              modify+=`
              <label class="checkbox-inline"><input type="checkbox" value="${item}" name="hobbies" checked> ${item}</label>
              `;
            } else {
              modify+=`
              <label class="checkbox-inline"><input type="checkbox" value="${item}" name="hobbies"> ${item}</label>
              `;
            }
          })
         
          modify+= `
          </div>
        </div>
        <button type="submit" class="btn btn-default">修改用户</button>
      </form>
        
      </body>
      </html>
      `;  
      res.end(modify)
    } else if(pathname == "/remove") {
      await user.findOneAndDelete({_id:query.id});
      res.writeHead(301,{
        Location:'/list'
      })
      res.end()
    }
  } else if(method == "POST"){
    //用户添加功能
    if(pathname == '/add') {
      //接受用户提交的信息
      let formData ='';
      //接受post参数
      req.on('data',param=>{
        formData+=param;
      })
      req.on('end',async ()=>{
        let userInfo = querystring.parse(formData);
        //将用户提交的信息添加到数据库
        await user.create(userInfo);
        res.writeHead(301,{
          Location:'/list'
        })
        res.end();
      })
    } else if(pathname == '/modify') {
        //接受用户提交的信息
        let formData ='';
        //接受post参数
        req.on('data',param=>{
          formData+=param;
        })
        req.on('end',async ()=>{
          let userInfo = querystring.parse(formData);
          //将用户提交的信息添加到数据库
          await user.updateOne({_id:query.id},userInfo);
          res.writeHead(301,{
            Location:'/list'
          })
          res.end();
        })
    }
  }
})

//监听端口
app.listen(3000);
console.log('服务器启动成功')